#（仅限windows系统）寻找某目录下的所有zip压缩包，提取其中的pfx证书文件及其密码，并导入该证书
# 必须使用管理员权限运行
# 每个压缩包内应该有一个.pfx文件和一个.txt文件，是证书及其对应的密码
param(
    [string]$Dir
)

$defaultCertDirName = "cert"
$certStore = "Cert:\LocalMachine\My"

if(-not $Dir){
    $Here = (Get-Location).Path
    $HereName = $Here | Split-Path -Leaf
    if($HereName.ToLower() -eq $defaultCertDirName){
        $Dir = $Here
    }
    else{
        $Dir = Get-ChildItem -Directory 
            | Where-Object{$_.Name.ToLower() -eq $defaultCertDirName}
            | Select-Object -ExpandProperty FullName -First 1
        if(-not $Dir){
            Write-Error "请传入-Dir参数，或在工作目录创建名为'cert'的目录"
            Exit
        }
    }
}else{
    $Dir = Resolve-Path -Path $Dir
}

Write-Host "开始导入目录[$($Dir)]内的证书" -ForegroundColor Blue
Set-Location -Path $Dir

$zipFiles = Get-ChildItem -Path . -Filter *.zip
foreach($zipFile in $zipFiles){
    $zipFileAssociateDir = $zipFile.Name | Split-Path -LeafBase
    Write-Host $zipFileAssociateDir.PadRight(40, '-')
    # 解压zip
    Expand-Archive -Path $zipFile.FullName -DestinationPath $zipFileAssociateDir -Force
    # 获取密码
    $passwordFileNameHere = Get-ChildItem -Path $zipFileAssociateDir -Filter *.txt | Select-Object -ExpandProperty FullName -First 1 
    if(-not $passwordFileNameHere){
        Write-Error "未找到存储密码的txt文件"
        Exit
    }
    $password = Get-Content $passwordFileNameHere
    $securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
    # 导入pfx
    $pfxFileNameHere = Get-ChildItem -Path $zipFileAssociateDir -Filter *.pfx | Select-Object -ExpandProperty FullName -First 1
    if(-not $pfxFileNameHere){
        Write-Error "未找到pfx文件"
        Exit
    }
    try{
        Import-PfxCertificate -FilePath $pfxFileNameHere -CertStoreLocation $certStore -Password $securePassword -ErrorAction Stop | Out-Null
    }
    catch{
        Write-Error "导入失败，可能：1.没有使用管理员权限 2.提供pfx对应的密码有误"
        Exit
    }
    Write-Host "成功导入到$($certStore)" -ForegroundColor Green
    
    Write-Host ''.PadRight(40, '-') 
}